package service

import (
	"context"
	"encoding/json"

	"task/driver"
	"task/models"

	log "github.com/sirupsen/logrus"
)

// StartDispatch start dispatch.
func StartDispatch(ctx context.Context, msg []byte) error {
	var err error
	// 解析消息
	event := new(models.DispatchEvent)
	if err = json.Unmarshal(msg, &event); err != nil {
		log.Errorf("Unmarshal message error(%v)", err)
		return err
	}
	// 调用调度接口
	if err = driver.CallDispatch(ctx, event); err != nil {
		return err
	}
	return nil
}

// StartCallback start dispatch.
func StartCallback(ctx context.Context, msg []byte) error {
	var err error
	// 解析消息
	event := new(models.CallbackEvent)
	if err = json.Unmarshal(msg, &event); err != nil {
		log.Errorf("Unmarshal message error(%v)", err)
		return err
	}
	// 调用调度接口
	if err = driver.CallDispatch(ctx, &models.DispatchEvent{
		Event:       models.DispatchEventBusinessCallback,
		ResourceId:  event.ResourceId,
		ProcessorId: event.ProcessorId,
		Result:      event.Result,
	}); err != nil {
		return err
	}
	return nil
}
